<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\ApiController;
use App\Http\Requests\Admin\StoreAdminRequest;
use App\Http\Requests\Admin\UpdateAdminRequest;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AdminController extends ApiController
{
    public function __construct()
    {
        // 权限检查
        $this->authorizePermission('manage_admins');
    }

    /**
     * 获取管理员列表
     */
    public function index(Request $request)
    {
        $admins = Admin::query()
            ->when($request->filled('username'), function ($query) use ($request) {
                $query->where('username', 'like', '%' . $request->username . '%');
            })
            ->when($request->filled('name'), function ($query) use ($request) {
                $query->where('name', 'like', '%' . $request->name . '%');
            })
            ->when($request->filled('status'), function ($query) use ($request) {
                $query->where('status', $request->status);
            })
            ->paginate(10);

        return $this->paginate($admins);
    }

    /**
     * 创建管理员
     */
    public function store(StoreAdminRequest $request)
    {
        $data = $request->validated();
        $data['password'] = Hash::make($data['password']);

        $admin = Admin::create($data);

        return $this->success($admin, '创建成功');
    }

    /**
     * 获取管理员详情
     */
    public function show(Admin $admin)
    {
        // 加载角色信息
        $admin->load('roles');

        return $this->success($admin);
    }

    /**
     * 更新管理员
     */
    public function update(UpdateAdminRequest $request, Admin $admin)
    {
        $data = $request->validated();

        // 如果有密码字段，则加密
        if (isset($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        }

        $admin->update($data);

        return $this->success($admin, '更新成功');
    }

    /**
     * 删除管理员
     */
    public function destroy(Admin $admin)
    {
        // 不能删除自己
        if ($admin->id === auth()->id()) {
            return $this->error('不能删除自己');
        }

        // 不能删除超级管理员
        if ($admin->hasRole('super_admin')) {
            return $this->error('不能删除超级管理员');
        }

        $admin->delete();

        return $this->success(null, '删除成功');
    }
}
